import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  DeviceEventEmitter,
  TextInput,
  TouchableOpacity,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';
import {
  Text,
  Container,
  Header,
  Left,
  Body,
  Right,
  Title,
  Item,
  List,
  ListItem,
  Thumbnail,
  Button,
  Icon,
  Image,

} from 'native-base';
import { produce } from 'immer';
import { UtilToast } from '../../../../utils/util-method';
import theme from '../../../../native-base-theme/variables/commonColor';
import {Loading, BlankBackground, ListFooter } from '../../../../components';
import * as sparePartService from '../../../../services/sparePart';

class Search extends Component {
  inputValue = '';

  page = 1;

  rows = 8;

  condition = '';

  // 构造方法
  constructor(props) {
    super(props);
    this.state = {
      errorTag: false,
      isError: false,
      showLoading: false,
      refreshing: false,
      listData: [],
      isMore: false,
    };
  }

  componentDidMount() {
    // this._onInitRefresh();
    this.swipeToSearchListhener = DeviceEventEmitter.addListener('swipeToSearch', this.queryInfoEvent);
  }


  componentWillUnmount() {
    if (this.swipeToSearchListhener) {
      this.swipeToSearchListhener.remove();
    }
  }

  queryInfoEvent = (v) => {
    if (this.state.listData.length === 0) {
      this._onInitRefresh();
    }
  }

  // 关注备件
  careSpare = async (index, item) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      let data = null;
      if (item.flag == '0') { // 取消关注
        data = await sparePartService.cancelCare({ id: item.id });
      } else { // 关注
        data = await sparePartService.care({ materialId: item.materialId });
      }
      DeviceEventEmitter.emit('showLoading', false);
      // if (data) {
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        if (draft.listData[index].flag == '1') {
          if (data.data) {
            draft.listData[index].id = data.data;
          }
          draft.listData[index].flag = '0';
        } else {
          draft.listData[index].flag = '1';
        }
      }));
      UtilToast(data.resultMsg, 'success');
      // }
    } catch (e) {
      console.log(e);
      UtilToast('关注失败', 'danger');
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  // 查询数据
  queryData = async (flag) => {

    const ajaxData = {
      condition: this.condition,
      page: this.page,
      rows: this.rows,
    };
    try {
      if (flag === 'search') {
        DeviceEventEmitter.emit('showLoading', true);
      }
      // console.log('===', ajaxData);
      // if (flag === 'refresh') {
      //   this.setState({ refreshing: true });
      // }
      const list = await sparePartService.querySpartPartListSearch(ajaxData);
      this.setState(produce(draft => {
        if (flag === 'refresh' || flag === 'search') {
          draft.listData = list.data;
        } else {
          draft.listData = draft.listData.concat(list.data);
        }
        draft.refreshing = false;
        draft.isMore = draft.listData.length < list.totalNum;
        DeviceEventEmitter.emit('showLoading', false);
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
      DeviceEventEmitter.emit('showLoading', false);
    }
  };

  // 搜索
  _onSearch = () => {
    this.condition = this.inputValue;
    // 关闭软键盘
    this.page = 1;
    TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField());
    this.queryData('search');
  };

  //  刷新时候获取数据
  _onRefresh = () => {
    this.page = 1;
    this.queryData('refresh');
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.page = this.page + 1;
      this.queryData('load');
    }
  }

  // 列表上拉加载没有数据时
  _renderListFooter = () => (
    (this.state.listData.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  tolist = () => {
    DeviceEventEmitter.emit('swiperIncidentPageEvent', 1);
  };

  //  错误页面刷新方法
  _onInitRefresh = () => {
    this.page = 1;
    this.queryData('search');
  }

  _onChangeText = v => {
    this.inputValue = v;
  };

  // 显示图片
  _showDetaiImage = (item) => {
    if (item.photos) {
      return {
        uri: `${sparePartService.getDownloadImg}/${item.photos}?token=${global.__TOKEN_ACCESS__}`,
      };
    }
    return require('../../../../../assets/images/no-pic.png');
  }

  // 每一行
  renderRow= (item) => {
    return (
      <TouchableOpacity>
        <View style={{ backgroundColor: '#ffffff', borderRadius: 8, marginLeft: 8, marginRight: 8, marginBottom: 8, paddingTop: 8, paddingBottom: 8  }}>
          <List>
            <ListItem onPress={() => this.cellAction(item)} thumbnail>
              <Left>
                <Thumbnail
                  style={{ backgroundColor: 'black', width: 80, height: 80, borderRadius: 4, marginLeft: 0 }}
                  square
                  source={this._showDetaiImage(item.item)}
                />
              </Left>
              <Body style={{ borderBottomWidth: 0, paddingTop: 0, paddingBottom: 0 }}>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Text style={[styles.Text, { flex: 1 }]} numberOfLines={1}>{item.item.materialCode1}</Text>
                  <TouchableWithoutFeedback onPress={() => this.careSpare(item.index, item.item)}>
                    <Icon
                      type="MaterialIcons"
                      name="favorite"
                      style={{ color: item.item.flag == '0' ? 'red' : '#686868', fontSize: 24, marginLeft: 20, marginRight: 8 }}
                    />
                  </TouchableWithoutFeedback>
                </View>
                <Text style={[styles.Text, { marginTop: 4, marginBottom: 4 }]} note numberOfLines={1}>名称：{item.item.materialName}</Text>
                <Text style={styles.Text} note numberOfLines={1}>型号：{item.item.materialSpecModel}</Text>
                <Text style={styles.Text} note numberOfLines={1}>库存量：{item.item.fisrtQuantity == null ? '0' : item.item.fisrtQuantity}</Text>
              </Body>
              {/* <Right>
                <Icon
                  type="MaterialIcons"
                  name="favorite-border"
                  style={{ color: '#686868' }}
                />
              </Right> */}
            </ListItem>
          </List>
        </View>
      </TouchableOpacity>

    );
  };

  // 点击某行
  cellAction = (item) => {
    const params = {
      code: item.item.materialCode1,
    };
    global.navigation.navigate({ routeName: 'SparePartInfo', params });
  };

  render() {
    const { listData, isError, refreshing } = this.state;
    let FlatListHtml;
    if (listData.length === 0) {
      FlatListHtml = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
    } else {
      FlatListHtml = (
        <FlatList
          data={listData}
          renderItem={item => this.renderRow(item)}
          keyExtractor={(item, index) => item + index}
          onRefresh={this._onRefresh}
          refreshing={refreshing}
          onEndReachedThreshold={0.05}
          scrollEventThrottle={200}
          onEndReached={this._onEndReached}
          ListFooterComponent={this._renderListFooter}
        />
      );
    }
    return (
      <Container style={styles.container}>
        <Header style={{ paddingTop: 0 }}>
          <Left />
          <Body>
            <Title>备件查询</Title>
          </Body>
          <Right />
        </Header>
        <Item style={styles.circle_container}>
          <Icon name="ios-search" style={styles.ios_search} />
          <TextInput
            style={styles.text_input}
            underlineColorAndroid="transparent"
            placeholder="备件名称/物料编码"
            onChangeText={this._onChangeText}
            onSubmitEditing={this._onSearch}
          />
          <TouchableOpacity style={{ padding: 10 }} onPress={this._onSearch}>
            <Text style={{ color: '#0391ff', fontSize: 14 }}>搜索</Text>
          </TouchableOpacity>
        </Item>
        {FlatListHtml}
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
    flex: 1,
    backgroundColor: theme.myPrimary,
  },
  Header: {
    width: '100%',
  },
  circle_container: {
    height: 40,
    borderRadius: 4,
    borderBottomWidth: 0,
    marginBottom: 8,
    marginLeft: 8,
    marginRight: 8,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  text_input: {
    flex: 1,
    marginLeft: 5,
    padding: 0,
    backgroundColor: 'white',
  },
  Text: {
    // backgroundColor: theme.myPrimary,
    // color: '#ffffff',
    fontSize: 15,
  },
  ios_search: {
    fontSize: 24,
    paddingLeft: 6,
    color: '#686868',
  },
});

export default Search;
